package com.tang.thepath.view;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;

import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;


import com.king.photo.activity.AlbumActivity;
import com.king.photo.activity.MainActivity;
import com.king.photo.util.Bimp;
import com.king.photo.util.FileUtils;
import com.king.photo.util.ImageItem;
import com.king.photo.util.PublicWay;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tang.thepath.GalleryActivity;
import com.tang.thepath.R;
import com.tang.thepath.adapter.GridAdapter;
import com.tang.thepath.model.RequestModel;
import com.tang.thepath.service.UploadService;
import com.tang.thepath.util.UtilPicSelector;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import rx.Observable;

public class ImageUploader extends RelativeLayout{

    private GridView noScrollgridview;
    private GridAdapter adapter;
    public static Bitmap bimap;
    private PopupWindow pop = null;
    private LinearLayout ll_popup;
    private View parentView;

    private List<LocalMedia> selectedList = new ArrayList<>();

    public List<Bitmap> getBitmapList() {
        return bitmapList;
    }

    private List<Bitmap> bitmapList = new ArrayList<>();

    View.OnClickListener popMenuClick = new OnClickListener() {
        @Override
        public void onClick(View view) {
            Activity context = (Activity)getContext();
            if(view.getId() == R.id.item_popupwindows_camera){
                //TODO 打开相机
                UtilPicSelector.openCamera(context, PictureMimeType.ofImage(),selectedList);
            }else if(view.getId() == R.id.item_popupwindows_Photo){
                //TODO 选择照片界面
                UtilPicSelector.openGallery(context, PictureMimeType.ofImage(),selectedList);
            }
            pop.dismiss();
            ll_popup.clearAnimation();
        }
    };

    public ImageUploader(Context context, AttributeSet attrs) {
        super(context, attrs);

        bimap = BitmapFactory.decodeResource(
                getResources(),
                R.drawable.icon_addpic_unfocused);
        //加载布局
        parentView = LayoutInflater.from(context).inflate(R.layout.view_image_uploader, this);
        Init(context);
    }

    public void Init(Context context) {
        pop = new PopupWindow(context);

        View view = LayoutInflater.from(context).inflate(R.layout.item_popupwindows, null);

        ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);

        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
        pop.setContentView(view);

        RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
        Button bt1 = (Button) view
                .findViewById(R.id.item_popupwindows_camera);
        Button bt2 = (Button) view
                .findViewById(R.id.item_popupwindows_Photo);
        Button bt3 = (Button) view
                .findViewById(R.id.item_popupwindows_cancel);


        parent.setOnClickListener(popMenuClick);
        bt1.setOnClickListener(popMenuClick);
        bt2.setOnClickListener(popMenuClick);
        bt3.setOnClickListener(popMenuClick);

        noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
        noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));

        //selectedList.add(new LocalMedia());//至少有一个对象，最后一个是加号按钮
        adapter = new GridAdapter(context);
        noScrollgridview.setAdapter(adapter);
        noScrollgridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long itemId) {
                if(position == selectedList.size()){
                    ll_popup.startAnimation(AnimationUtils.loadAnimation(getContext(),R.anim.activity_translate_in));
                    pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
                }else{
                    Intent intent = new Intent(getContext(),
                            GalleryActivity.class);
                    //intent.putExtra("position", "1");

                    Bundle bundle = new Bundle();
                    bundle.putInt("ID",position);
                    bundle.putSerializable("bitmapList",(Serializable)selectedList);
                    intent.putExtras(bundle);
                    ((Activity)getContext()).startActivityForResult(intent,GalleryActivity.RESULT);
                }
            }
        });
        //adapter.setDataList(this.selectedList);
        refresh(this.selectedList);
        //adapter.update();

    }

    private List<Bitmap> createBitmapList(List<LocalMedia> selectedList){
        List<Bitmap> bitmapList = new ArrayList<>();
        for (int i=0;i<selectedList.size();i++){
            Bitmap bitmap = BitmapFactory.decodeFile(selectedList.get(i).getCompressPath());
            bitmapList.add(bitmap);
        }
        return bitmapList;
    }


    public void refresh(List<LocalMedia> selectedList){
        this.selectedList = selectedList;
        List<Bitmap> tempBitmapList = this.bitmapList;
        this.bitmapList = createBitmapList(selectedList);
        //this.selectedList.add(new LocalMedia());
        adapter.setDataList(this.bitmapList);
        adapter.notifyDataSetChanged();
        for (int i=0;i<tempBitmapList.size();i++){
            tempBitmapList.get(i).recycle();
        }
    }

    public Observable<RequestModel.UploadResponse> uploadImages(){
        List<File> uploadList = new ArrayList<>();
        for (int i=0;i<selectedList.size();i++){
            uploadList.add(new File(selectedList.get(i).getCompressPath()));
        }

        return UploadService.uploadImages(uploadList);
    }

    public int imageCount(){
        return selectedList.size();
    }
}
